package auth

import (
	"encoding/base64"
	"go-proxy/config"
	"net/http"
	"strings"
)

type HttpBasicAuth struct {
}

func NewHttpBasicAuth() *HttpBasicAuth {
	return &HttpBasicAuth{}
}

func (h *HttpBasicAuth) checkAuth(w http.ResponseWriter, r *http.Request, auth *config.Auth) bool {
	// 获取 Authorization 头
	authHeader := r.Header.Get("Authorization")
	if authHeader == "" {
		// 如果没有提供认证信息，返回 401 并设置 WWW-Authenticate 头
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 解析 Authorization 头
	authParts := strings.SplitN(authHeader, " ", 2)
	if len(authParts) != 2 || authParts[0] != "Basic" {
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 解码 Base64 编码的用户名和密码
	decoded, err := base64.StdEncoding.DecodeString(authParts[1])
	if err != nil {
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 分割用户名和密码
	secret := strings.SplitN(string(decoded), ":", 2)
	if len(secret) != 2 {
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}

	// 检查用户名和密码是否正确
	if !checkAuth(secret[0], secret[1], auth) {
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return false
	}
	return true
}

// checkAuth 函数用于检查提供的用户名和密码是否正确
func checkAuth(username, password string, auth *config.Auth) bool {
	configs := auth.HttpBasic
	if len(configs) <= 0 {
		return false
	}

	for _, item := range configs {
		if item.Username == username && item.Password == password {
			return true
		}
	}
	return false
}
